﻿using System;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;

namespace FrameServer
{
    static class LogUtil
    {
        //Log一天一个文件
        private static string filePath =>$"Logs/{DateTime.Now.ToString("yyyy年MM月dd日", DateTimeFormatInfo.InvariantInfo)}Log.txt";
        
        private static StreamWriter streamWriter = null;
        private static StreamWriter OpenLogFile() {
            if (streamWriter != null)
                return streamWriter;
            FileInfo fileInfo = new FileInfo(filePath);
            if (!fileInfo.Directory.Exists)
                Directory.CreateDirectory(fileInfo.DirectoryName);
            if (!fileInfo.Exists)
                fileInfo.Create().Close();

            streamWriter = new StreamWriter(filePath, true);
            streamWriter.WriteLine();
            streamWriter.WriteLine($"---------------------{DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒", DateTimeFormatInfo.InvariantInfo)}------------------------");
            return streamWriter;
        }
        public static void Log(object log, LogLevel logLevel = LogLevel.INFO)
        {
            StreamWriter streamWriter = OpenLogFile();
            string outLog = $"[{logLevel} {DateTime.Now.ToString("HH:mm:ss.fff", DateTimeFormatInfo.InvariantInfo)}] {log}";
            if (logLevel == LogLevel.WARN)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
            }
            else if (logLevel == LogLevel.EROR)
            {
                Console.ForegroundColor = ConsoleColor.Red;
            }
            Console.WriteLine(outLog);
            Console.ResetColor();

            streamWriter.WriteLine(outLog);
            streamWriter.Flush();
        }

        public static void Info(object log)
        {
            Log(log, LogLevel.INFO);
        }

        public static void Warn(object log)
        {
            Log(log, LogLevel.WARN);
        }

        public static void Error(object log)
        {
            Log(log, LogLevel.EROR);
        }

        public static void Init()
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                var ex = (Exception)e.ExceptionObject;
                Error(ex);
            };
        }
    }
    public enum LogLevel { 
        INFO,
        WARN,
        EROR
    }
}
